package com.linxiao.payment.business.impl.wx;

import com.alibaba.fastjson2.JSONObject;
import com.egzosn.pay.common.bean.CertStoreType;
import com.egzosn.pay.wx.v3.api.WxPayConfigStorage;
import com.egzosn.pay.wx.v3.api.WxPayService;
import com.egzosn.pay.wx.v3.bean.WxTransferType;
import com.egzosn.pay.wx.v3.bean.transfer.TransferDetail;
import com.egzosn.pay.wx.v3.bean.transfer.WxTransferOrder;
import com.linxiao.payment.business.TransferManager;
import com.linxiao.payment.vo.TransferRequest;
import com.linxiao.payment.core.constants.IfCodeEnum;
import com.linxiao.payment.web.domain.PayInterfaceConfig;
import com.linxiao.payment.web.service.IPayInterfaceConfigService;
import com.ruoyi.common.exception.base.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;

/**
 * 支付宝转账
 * @author zhoudong
 */
@Component
public class WxPayTransferManager implements TransferManager {
    private static final Logger LOG = LoggerFactory.getLogger(WxPayTransferManager.class);
    @Resource
    private IPayInterfaceConfigService payInterfaceConfigService;

    /**
     * 转账
     * @param transferRequest 转账实体
     */
    public Map<String, Object> transfer(TransferRequest transferRequest) {
        WxPayService service = init(transferRequest.getMchId());

        WxTransferOrder order = new WxTransferOrder();
        order.setOutBatchNo(transferRequest.getOutBizNo());
        order.setBatchName(transferRequest.getTitle());
        order.setBatchRemark(transferRequest.getRemark());
        // 转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致，否则无法发起转账操作
        order.setTotalAmount(transferRequest.getTransAmount().multiply(BigDecimal.valueOf(100)));
        //一个转账批次单最多发起一千笔转账。转账总笔数必须与批次内所有明细之和保持一致，否则无法发起转账操作
        order.setTotalNum(1);
        TransferDetail transferDetail = new TransferDetail();
        transferDetail.setOutDetailNo(transferRequest.getOutBizNo() + "01");
        // 转账金额单位为“分”。转账总金额必须与批次内所有明细转账金额之和保持一致，否则无法发起转账操作
        transferDetail.setTransferAmount(transferRequest.getTransAmount().multiply(BigDecimal.valueOf(100)).intValue());
        transferDetail.setTransferRemark(transferRequest.getRemark());
        transferDetail.setOpenid("商户appid下，某用户的openid");
        transferDetail.setUserName(transferRequest.getName());
        order.setTransferDetailList(Collections.singletonList(transferDetail));
        //发起商家转账,转账到零钱
        order.setTransferType(WxTransferType.TRANSFER_BATCHES);

        Map<String, Object> transfer = service.transfer(order);
        LOG.info("微信转账，返回：{}", transfer);
        return transfer;
    }

    /**
     * 初始化商户
     *
     * @return
     * @param mchId
     */
    private WxPayService init(String mchId) {
        PayInterfaceConfig payInterfaceConfig = payInterfaceConfigService.selectByMchIdAndIfCode(Long.parseLong(mchId), IfCodeEnum.ALIPAY_TRANSFER);
        if (payInterfaceConfig == null) {
            throw new BaseException("当前商户未配置支付宝出款信息，商户ID：" + mchId);
        }
        JSONObject params = JSONObject.parseObject(payInterfaceConfig.getIfParams());

        WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage();
        wxPayConfigStorage.setAppId(params.getString("appId"));
        wxPayConfigStorage.setMchId(params.getString("mchId"));
        //V3密钥 https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay3_2.shtml
        wxPayConfigStorage.setV3ApiKey(params.getString("apiV3Key"));
        wxPayConfigStorage.setInputCharset(StandardCharsets.UTF_8.name());
        //使用证书时设置为true
//        wxPayConfigStorage.setCertSign(true);
        //商户API证书 https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay3_1.shtml
        wxPayConfigStorage.setApiClientKeyP12(params.getString("cert"));
        wxPayConfigStorage.setCertStoreType(CertStoreType.PATH);

        return new WxPayService(wxPayConfigStorage);
    }
}
